/*
 * Created on Jun 30, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.peterrussell.contractionTimer.model;

/**
 * @author peterr
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class ContractionTimeDAO {

	
	private static ContractionTimeDTO[] timesArray = new ContractionTimeDTO[0];
	private static final int MAX_ARRAY_SIZE = 100; 
	
	public static ContractionTimeDTO getDTO(int index) {
		return timesArray[index];
	}
	
	public static ContractionTimeDTO getDTO() {
		return new ContractionTimeDTO();
	}
	
	public static void setDTO(ContractionTimeDTO dto) {
		if (dto.isNew()) {
			add(dto);
		} else {
			timesArray[dto.getIndex()] = dto;
		}
	}
	
	private static void add(ContractionTimeDTO dto) {
		ContractionTimeDTO[] newArray = new ContractionTimeDTO[timesArray.length+1];
		if (timesArray.length > MAX_ARRAY_SIZE) {
		    System.arraycopy(timesArray, 1, newArray, 0, timesArray.length-1);
		} else if (timesArray.length > 0) {
		    System.arraycopy(timesArray, 0, newArray, 0, timesArray.length);
		}
		
		dto.setIndex(timesArray.length);
		// Set 'Business' Data
		getAverages(dto);
		newArray[timesArray.length] = dto;
		timesArray = newArray;
	}

	private static void getAverages(ContractionTimeDTO dto) {
		int max = timesArray.length>2?2:timesArray.length;
		long totalContaction = dto.getContractionTime();
		long totalBetweenContaction = dto.getBetweenContractionTime();
		for (int i = 0; i < max; i++) {
			totalContaction += timesArray[i].getContractionTime();
			totalBetweenContaction += timesArray[i].getBetweenContractionTime();
		}
		dto.setContractionTimeAvgOf(max+1);
		dto.setContractionTimeAvg(totalContaction/(max+1));
		dto.setBetweenContractionTimeAvgOf(max+1);
		dto.setBetweenContractionTimeAvg(totalBetweenContaction/(max+1));
	}
	/**
	 * @return Returns the timesArray.
	 */
	public static ContractionTimeDTO[] getTimesArray() {
		return timesArray;
	}
	/**
	 * @param timesArray The timesArray to set.
	 */
	public static void setTimesArray(ContractionTimeDTO[] timesArray) {
		ContractionTimeDAO.timesArray = timesArray;
	}
}
